/**
 *消息发送框工具条.  
 */
var MsgEditorToolbar = (function() {
    function _msgEditorToolbar(chatPanel) {
        var _this = this;
        this.chatPanel = chatPanel;
        
        function upfiles(files){
            if(Type.isArray(files)){
                $.each(files, function(index, file){
                    upfiles(file);           
                });
                return;
            } else {
                var file = files;  
                              
                if(ujs.browser.file.isImage(file)){                
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        ujs.browser.img.getSize(file).done(function(width, height){                            
                            var imgSize = new Size(width, height);
                            var constraintResult = imgSize.constraint(1000,1000); 
                            if(!constraintResult){
                                ujs.browser.img.genThumbnail({
                                    src : e.target.result,
                                    type : file.type,
                                    width : 200,
                                    isGetImgFileObj : true
                                }, function(thumbImgFile, thumbnailBase64, src, b64){                             
                                    MsgSender.send('image', {
                                        imgFile : file,
                                        thumbImgFile : thumbImgFile,
                                        thumbnailBase64 : thumbnailBase64,
                                        width : b64.width,
                                        height : b64.height
                                    });                       
                                });
                            } else {                                
                                //先生成1000以内的图片.
                                ujs.browser.img.genThumbnail({
                                    src : e.target.result,
                                    type : file.type,
                                    width : imgSize.width,
                                    height : imgSize.height,
                                    isGetImgFileObj : true
                                }, function(thumbImgFile, thumbnailBase64){
                                    ujs.browser.img.genThumbnail({
                                        src : e.target.result,
                                        type : file.type,
                                        width : 200,
                                        isGetImgFileObj : true
                                    }, function(thumbImgFile1, thumbnailBase641, src, b64){                             
                                        MsgSender.send('image', {
                                            imgFile : thumbImgFile,
                                            thumbImgFile : thumbImgFile1,
                                            thumbnailBase64 : thumbnailBase641,
                                            width : b64.width,
                                            height : b64.height
                                        });                       
                                    });               
                                });
                            }
                        });                        
                    };            
                    reader.readAsDataURL(file);
                } else {  
                    MsgSender.send('file', {
                        file :file
                    });
                }
            }
        }
        
        _this.upfiles = upfiles;
        
        //用户有那些消息类型可以发送.
        var perm = this.chatPanel.chatGroupEntity.perm;
        
        var ctype = this.chatPanel.chatGroupEntity.type

        var funPerm = perm['func'] || [];
        
        if(!perm['re']){
            this.chatPanel.disableChatEditor();
        } else {
            var _msgEditorToolbar = chatPanel.getMsgboxToolbarPlaceholder().toolbar({
                cls : 'disperse'
            }).data('toolbar');   
            _this.toolbar = _msgEditorToolbar;       
            //sticker
            if(funPerm.contains('sti')){
                _msgEditorToolbar.addImageButton({
                    id : 'face',
                    image : ujs.getRes('images/common16/face.png'),
                    tooltip : 'Send Sticker',
                    cls : 'icon imageBtn',
                    onClick : function() {                        
                        if (emojiSelectorTab.isVisible()) {
                            emojiSelectorTab.hide();
                        } else {
                            emojiSelectorTab.show(this);
                            (function(){
                                emojiSelectorTab.getTabControl().selectFirstVisibleTab(true);
                            }).defer();                            
                        }
                    }
                });
            }        
            
            //_msgEditorToolbar.addSep();
               
            //upload
            if(funPerm.containsAtLeastOne('img', 'file', 'vid', 'aud')){
                _msgEditorToolbar.addImageButton({
                    id : 'upload',
                    image : ujs.getRes('images/common16/upload.png'),
                    tooltip : 'Upload Image/File',
                    cls : 'icon imageBtn',
                    onClick : function() {
                        ujs.browser.file.openFileSelector({}, upfiles);
                    }
                });
            }
            //share location
            _msgEditorToolbar.addImageButton({
                id : 'mapLoc',
                image : ujs.getRes('images/common16/map_loc.png'),
                tooltip : 'Share Location',
                cls : 'icon imageBtn',
                onClick : function() {                    
                    var dialog = new ShareLocDialog({
                        mode : 'edit',
                        bodyStyle : 'margin:0px',
                        toolbar : false
                    });
                    dialog.on('share', function(latLng, place){                        
                        if(place){
                            //业务上取第一个最详细的地址位置.
                            latLng = place[0].geometry.location;
                        }
                        latLng.zoom = this.map.getZoom();
                        MsgSender.send('location', latLng);                
                        this.hide();
                    });
                    dialog.show();      
                }
            });


            if(ctype == 'singlechat'){
                _msgEditorToolbar.addSep({});
            }
            
            if(ctype == 'singlechat'){
                
                _msgEditorToolbar.addImageButton({
                    id : 'hiddenChat',
                    image : ujs.getRes('images/common16/lock.png'),
                    tooltip : 'Destruct Chat',
                    cls : 'icon imageBtn',
                    onClick : function() {                    
                        var teid = ChatPanel.getActiveChatPanel().chatGroupEntity['id'];
                        
                        //若已存在相关会话，则直接启动.
                        var result = page.chatGroupStore.items.filter(function(item){
                            if(item && item['te']['obj']['rtype'] == 'destruct' && item['te']['obj']['relate'] == teid) 
                            return item;
                        })                    
                        if(result && result.length){
                            sessionList.startSession(result[0]['id']);
                            return;
                        }
                        //创建相关会话.
                        var te = page.chatGroupStore.getItem(teid);
                        var pids = te['te']['obj']['participants'].map(function(item){return item.id;});
                        var partis = page.biz.getParticipant(te['te']);                    
                        var data = {
                            type : 'adminchat',
                            ugids : [],
                            uids : pids,
                            auids : [ ujs.util.session.getCurrentUserID()],
                            title : te['name'],
                            description : '',
                            icon : partis['icon'], 
                            relate : teid,
                            rtype : 'destruct'  //location
                        };                          
                        $.extend(data, ChatGroupPerm.props, {
                            allowParticipant : true,
                            allowChat : true,
                            allowLocation : false,
                            allowDestruct : true,
                            allowBroadcast : false
                        });
                        //chat group图标.
                        var formData = Object.toFormData({
                            chat : JSON.stringify(data)
                        });                   
                        page.biz.createChatGroup(formData, function(msg){                                
                            page.biz.addChatGroupLocal(msg);                                    
                            sessionList.startSession(msg['te']['id']);
                        }, function(){});
                    }
                });
            
            }
            
            
            if(ctype == 'singlechat'){
                    
               _msgEditorToolbar.addImageButton({
                    id : 'locChat',
                    image : ujs.getRes('images/common16/marker.png'),
                    tooltip : 'Location Chat',
                    cls : 'icon imageBtn',
                    onClick : function() {                    
                        var teid = ChatPanel.getActiveChatPanel().chatGroupEntity['id'];
                        
                        //若已存在相关会话，则直接启动.
                        var result = page.chatGroupStore.items.filter(function(item){
                            if(item && item['te']['obj']['rtype'] == 'location' && item['te']['obj']['relate'] == teid) 
                            return item;
                        })             
                        if(result && result.length){
                            sessionList.startSession(result[0]['id']);
                            return;
                        }
                        //创建相关会话.
                        var te = page.chatGroupStore.getItem(teid);
                        var pids = te['te']['obj']['participants'].map(function(item){return item.id;});
                        var partis = page.biz.getParticipant(te['te']);                    
                        var data = {
                            type : 'adminchat',
                            ugids : [],
                            uids : pids,
                            auids : [ ujs.util.session.getCurrentUserID()],
                            title : te['name'],
                            description : '',
                            icon : partis['icon'], 
                            relate : teid,
                            rtype : 'location'  //location
                        };                          
                        $.extend(data, ChatGroupPerm.props, {
                            allowParticipant : true,
                            allowChat : true,
                            allowLocation : true,
                            allowDestruct : false,
                            allowBroadcast : false
                        });
                        //chat group图标.
                        var formData = Object.toFormData({
                            chat : JSON.stringify(data)
                        });                   
                        page.biz.createChatGroup(formData, function(msg){                                
                            page.biz.addChatGroupLocal(msg);                                    
                            sessionList.startSession(msg['te']['id']);
                        }, function(){});
                    }
                });
            
            }
                        
            _msgEditorToolbar.addCheckbox({
                name : 'sendActionType',
                labelPos : 'right',
                isChecked : Boolean(parseInt($.cookie('chatSendType'))),
                text : 'Ctrl + Enter to send',
                align : 'right',
                style : 'letter-spacing:1px;font-weight:bold;',
                onChange : function(isSelected){
                    $.cookie('chatSendType', Number(isSelected), {
                        expires : Date.nowDateObj().add('y', 1000)
                    });
                }
            });            
        }
    }
    return _msgEditorToolbar;
})(); 